package org.example.common;

import com.seaway.models.sec06.*;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
public class GrpcClient {
    private static final Logger LOG = LoggerFactory.getLogger(GrpcServer.class);

    private static void transfer() throws InterruptedException {
        var channel = ManagedChannelBuilder
                .forAddress("localhost", 5555)
                .usePlaintext()
                .build();
        var requests = List.of(
                TransferRequest.newBuilder().setAmount(10).setFromAccount(1).setToAccount(1).build(),
                TransferRequest.newBuilder().setAmount(10).setFromAccount(1).setToAccount(2).build(),
                TransferRequest.newBuilder().setAmount(10).setFromAccount(1).setToAccount(2).build(),
                TransferRequest.newBuilder().setAmount(10).setFromAccount(1).setToAccount(2).build()
        );
       var transferServiceStub = TransferServiceGrpc.newStub(channel);
        var requestStreamObserver = transferServiceStub.transfer(new StreamObserver<TransferResponse>() {
            @Override
            public void onNext(TransferResponse transferResponse) {
                LOG.info("client received data is :{},{}",transferResponse,transferResponse.getStatus());
            }

            @Override
            public void onError(Throwable throwable) {
                LOG.error("$$$$$$$$$$$$$$$$$$$$$$$$$$$$===>{}",throwable.getMessage());
            }

            @Override
            public void onCompleted() {

            }
        });
        for (int i = 0; i < 100; i++) {
           LOG.info("client send :{}",i);
           TimeUnit.SECONDS.sleep(1);
           if(i==500){
               requestStreamObserver.onError(new RuntimeException("client test error"));
           }else{
               requestStreamObserver.onNext(requests.get(0));
           }

        }
        System.out.println("over");
     //  requestStreamObserver.onCompleted();
        TimeUnit.SECONDS.sleep(50);
    }
    public static void main(String[] args) throws InterruptedException {
        transfer();
    }
}
